package cn.reone.mbt.ui;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.orhanobut.logger.Logger;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.reone.mbt.R;

/**
 * Created by wangxingsheng on 2017/3/6.
 */

public class DeviceAdapter extends BaseAdapter {

    private ArrayList<BluetoothDevice> mPairedDevices;
    private LayoutInflater mInflater;

    public DeviceAdapter(ArrayList<BluetoothDevice> pairedDevices, Context context) {
        Logger.d("新建Adapter,初始数据条目数: "+pairedDevices.size());
        mPairedDevices = pairedDevices;
        mInflater = LayoutInflater.from(context);
    }

    public ArrayList<BluetoothDevice> getPairedDevices(){
        return mPairedDevices;
    }

    @Override
    public int getCount() {
        return mPairedDevices.size();
    }

    @Override
    public BluetoothDevice getItem(int position) {
        return mPairedDevices.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.device_item, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        BluetoothDevice device = mPairedDevices.get(position);
        if(device != null){
            holder.textView2.setText("name:" + device.getName());
            holder.textView3.setText("address:" + device.getAddress());
            holder.textView4.setText("state:" + device.getBondState());
        }
        return convertView;
    }

    public void reflush(ArrayList<BluetoothDevice> more){
        Logger.d("更新数据"+more.size());
        mPairedDevices = more;
        notifyDataSetChanged();
    }
    public void add(BluetoothDevice onemore){
        mPairedDevices.add(onemore);
        notifyDataSetChanged();
        Logger.d("更新一条数据"+onemore.getName()+" -> "+onemore.getAddress());
    }

    public void clear() {
        mPairedDevices.clear();
        notifyDataSetChanged();
        Logger.d("清空列表数据");
    }

    static class ViewHolder {
        @BindView(R.id.textView2)
        TextView textView2;
        @BindView(R.id.textView3)
        TextView textView3;
        @BindView(R.id.textView4)
        TextView textView4;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
